package com.taotao.manage;

import com.taotao.chain.GatewayHandler;
import com.taotao.entity.GatewayHandlerEntity;
import com.taotao.mapper.GatewayHandlerMapper;
import com.taotao.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: wangjin
 * @CreateTime: 2022-06-26  13:27
 */
@Slf4j
@Component
public class GatewayHandlerManage {
    @Autowired
    private GatewayHandlerMapper gatewayHandlerMapper;

    public GatewayHandler getFirstGatewayHandler() throws Exception {

        GatewayHandlerEntity firstGatewayHandler = gatewayHandlerMapper.getFirstGatewayHandler();
        //先查询第一个gatewayHandler
        if (firstGatewayHandler == null) {
            //db没有配置第一个
            log.error("没有配置我们的第一个gatewayHandler");
            return null;
        }
        String firstHandlerId = firstGatewayHandler.getHandlerId();
        if (Strings.isEmpty(firstHandlerId)) {
            log.error("没有配置我们的第一个firstHandlerId");
            return null;
        }
        //2 继续 判断如果有下一个gatewayHandler直接调用gatewayHandler.setGatewayHandler();
        GatewayHandler firstHandler = SpringUtils.getBean(firstHandlerId, GatewayHandler.class);
        String nextHandlerId = firstGatewayHandler.getNextHandlerId();
        GatewayHandler tempHandlers=firstHandler;
        while (Strings.isNotBlank(nextHandlerId)) {
            GatewayHandler nextGatewayHandler = SpringUtils.getBean(nextHandlerId, GatewayHandler.class);
            tempHandlers.setNextGatewayHandler(nextGatewayHandler);
            //根据nextGatewayHandler查询数据库db信息得到下一个GatewayHandler信息
            GatewayHandlerEntity nextGatewayHandlerEntity = gatewayHandlerMapper.getByHandler(nextHandlerId);
            nextHandlerId = nextGatewayHandlerEntity.getNextHandlerId();
            tempHandlers=nextGatewayHandler;
        }

        return firstHandler;
    }
}
